package com.dc.datacollect.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dc.datacollect.components.cache.Cache;
import com.dc.datacollect.components.upload.FileResponseServerController;
import com.dc.datacollect.components.upload.FileUploadService;
import com.dc.datacollect.conduit.R;
import com.dc.datacollect.constant.type.UserSessionActivityKey;
import com.dc.datacollect.dto.input.CreateCollectInput;
import com.dc.datacollect.dto.input.SubmitCollectInput;
import com.dc.datacollect.dto.output.*;
import com.dc.datacollect.entity.Collect;
import com.dc.datacollect.entity.CollectInstance;
import com.dc.datacollect.service.CollectInstanceService;
import com.dc.datacollect.service.CollectService;
import com.dc.datacollect.service.PermitService;
import com.dc.datacollect.helpers.SessionProvide;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;

/**
 * 收集者控制器
 *
 * @author zhuangjie
 * @date 2023/06/19
 */
@RestController
@RequestMapping("/collect")
public class CollectController {
    @Autowired
    private CollectService collectService;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private PermitService permitService;

    @Autowired
    FileResponseServerController fileResponseServerController;

    @Autowired
    private CollectInstanceService collectInstanceService;

    @Autowired
    private Cache cache;

    @PostMapping("/create")
    public R create(@Valid @RequestBody CreateCollectInput createCollectInput) throws Exception {
        return R.auto(collectService.createCollect(createCollectInput));
    }

    @GetMapping("/getWaitSubmitAndNotExpire")
    public R getWaitSubmitAndNotExpir() {
        Long userId = SessionProvide.getLoginObject().getId();
        return R.ok("查询有效可提交的收集信息").data(collectService.getWaitSubmitAndNotExpire(userId));
    }

    @GetMapping("/getInProgressCollect")
    public R getInProgressCollect() {
        Long userId = SessionProvide.getLoginObject().getId();
        List<InProgressCollectOutput> inProgressCollectOutputs = collectService.getInProgressCollect(userId);
        return R.ok("查询正在进行中的收集表").data(inProgressCollectOutputs);
    }

    @PostMapping ("/upload")
    public R uploadImage(@NotNull Long collectId,@NotNull MultipartFile file) throws Exception {
        String imgUrl = fileUploadService.MultipartFileToUrl(file);
        // 获取前缀名
        String filename = file.getOriginalFilename();
        String separate = ".";
        if (filename.contains(separate)) {
            filename = filename.substring(0, filename.lastIndexOf(separate));
        }
        // 将文件放到Session，然后返回成功即可。
        if (imgUrl != null && ! imgUrl.isEmpty()) {
            SessionProvide.set(UserSessionActivityKey.COLLECT_FILE_KEY+collectId,imgUrl);
            SessionProvide.set(UserSessionActivityKey.COLLECT_FILENAME_KEY+collectId,filename);
        }
        return R.ok("上传成功");
    }
    @PostMapping("/submitCollect")
    public R submitCollect(@Valid @RequestBody SubmitCollectInput submitCollectInput) throws Exception {
        Boolean isSuccess = collectService.submitCollect(submitCollectInput);
        return R.auto("提交收集成功",isSuccess);
    }

    @GetMapping("/getSubmittableCount")
    public R getSubmittableCount() throws Exception {
        Integer submittableCount = collectService.selectWaitSubmitCount(SessionProvide.getLoginObject().getId());
        return R.ok("获取可提交收集表成功").data(submittableCount);
    }
    @GetMapping("/getHistoryCollectList")
    public R getHistoryCollectList(@RequestParam("currentPage") Integer currentPage,
                                   @RequestParam("pageSize") Integer pageSize,
                                   @RequestParam("keyword") String keyword,
                                   @RequestParam("type") Short type) throws Exception {
        // 查出用户要参考的活动 且活动已经结束的 通过 keyword过滤 根据type不可 not in / in
        Page<EndedCollectOutput> endedCollectOutputPage = collectService.getHistoryCollectList(new Page<>(currentPage, pageSize),keyword,type);
        return R.ok("获取数据已经结束的收集成功").dataAsMap(m->{
            m.put("list",endedCollectOutputPage.getRecords());
            m.put("total",endedCollectOutputPage.getTotal());
        });
    }
    @GetMapping("/download")
    public R download(@NotNull @RequestParam("collectId") String collectId, HttpServletResponse response) throws Exception {
        LambdaQueryWrapper<CollectInstance> collectInstanceQueryWrapper = new LambdaQueryWrapper<>();
        collectInstanceQueryWrapper.eq(CollectInstance::getCollectId,collectId);
        CollectInstance collectInstance = collectInstanceService.getOne(collectInstanceQueryWrapper);
        if (collectInstance == null ) {
            throw new Exception("操作错误，你未提交收集活动作品，无法下载。");
        }
        String fileUrl = collectInstance.getFile();
        // 想要在这里重定向上面的文件url,让前端下载
        return R.ok().data(fileUrl+"?filename="+collectInstance.getFileName());
    }

    @GetMapping("/consoleCollectPageData")
    public R consoleCollectPageData(@RequestParam("currentPage") Integer currentPage,
                                   @RequestParam("pageSize") Integer pageSize,
                                   @RequestParam("keyword") String keyword) throws Exception {
        Page<ConsoleCollectOutput> dataPage = collectService.consoleCollectPageData(new Page<>(currentPage, pageSize),keyword);
        return R.ok("获取控制台分页数据成功").dataAsMap(m->{
            m.put("total",dataPage.getTotal());
            m.put("list",dataPage.getRecords());
        });
    }

    @GetMapping("/exportCollect/{collectId}")
    public  R exportCollect(@PathVariable("collectId") Long collectId) throws Exception {
        String zipDownloadUrl = collectService.exportCollect(collectId);
        return R.ok("导出操作执行成功").data(zipDownloadUrl);
    }

    @PostMapping("/remove/{collectId}")
    public R remove(@PathVariable("collectId") Long collectId) throws Exception {
        Boolean isSuccess = collectService.removeCollectById(collectId);
        return R.auto("删除收集活动",isSuccess);
    }

    @PostMapping("/edit")
    public R edit(@RequestBody Collect collect) throws Exception {
        Boolean updateSuccess = collectService.updateCollect(collect);
        return R.auto("更新收集活动信息",updateSuccess);
    }

    @GetMapping("/collectUserPage")
    public R collectUser(@RequestParam("currentPage") Integer currentPage,
                         @RequestParam("pageSize") Integer pageSize,
                         @RequestParam("collectId") Long collectId,
                         @RequestParam("keyword") String keyword,
                         @RequestParam("groupId") Long groupId,
                         @RequestParam("status") Short status ) {
        Page<CollectUserOutput> collectUserOutputs = collectService.selectCollectUserPage(new Page<>(currentPage,pageSize),collectId,keyword,groupId,status);
        return R.ok("查询收集活动的用户及相关").dataAsMap(m->{
            m.put("list",collectUserOutputs.getRecords());
            m.put("total",collectUserOutputs.getTotal());
        });
    }

    @GetMapping("/selectCollectGroupList/{collectId}")
    public R selectCollectGroupList(@PathVariable("collectId") Long collectId) {
         List<CollectAssociatedGroupOutput> collectAssociatedGroupList = collectService.selectCollectGroupList(collectId);
         return R.ok("获取收集活动相关联的组成功").data(collectAssociatedGroupList);
    }

    @PostMapping("/expeditingAll/{collectId}")
    private R expediting(@PathVariable("collectId") Long collectId) throws Exception {
        collectService.expediting(collectId);
        return R.ok("后台执行中，结束后将通过邮件通知您！");
    }


}
